package com.incar.chuxing.activity.certification;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.ocr.sdk.model.IDCardParams;
import com.google.gson.Gson;
import com.incar.chuxing.R;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CommitDriveLicenseBean;
import com.incar.chuxing.bean.UploadImageBaidu;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.bos.UploadPicUtil;
import com.incar.chuxing.utils.ocrlicense.FileUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class CertifyDrivelicenseActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_name)
    TextView titleName;
    @BindView(R.id.title_more)
    ImageView titleMore;
    @BindView(R.id.title_tv_more)
    TextView titleTvMore;
    @BindView(R.id.iv_drive_qian)
    ImageView ivDriveQian;
    @BindView(R.id.iv_drive_hou)
    ImageView ivDriveHou;
    @BindView(R.id.tv_next)
    TextView tvNext;
    private Context mContext = this;
    private int submitType;
    private String drivingCard;
    private String filePath;
    private File originalFile;
    private File compressFile;
    private String[] picKeyArray = new String[]{"", "", "", "", ""};

    private boolean flag3;
    private boolean flag4;
    private boolean flag;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    showLoadingDialog();
                    break;
                case 2:
                    //成功压缩
                    //上传图片
                    uploadImage(compressFile);
                    break;
                case 3:
                    //压缩失败
                    dismissLoadingDialog();
                    picKeyArray[submitType] = "";
                    ToastUtils.makeText(mContext, "图片上传失败，请重试", ToastUtils.LENGTH_SHORT).show();
                    break;
                case 4: //上传成功
                    dismissLoadingDialog();

                    if (submitType == 3) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, ivDriveQian);
                        flag3 = true;
                    } else if (submitType == 4) {
                        ImageLoader.getInstance().displayImageFitCenter(mContext, compressFile, ivDriveHou);
                        flag4 = true;
                    }
                    if (flag3 & flag4) {
                        tvNext.setBackgroundResource(R.drawable.btn_bg);
                        tvNext.setEnabled(true);
                    }
                    break;
                case 5:
                    //上传失败
                    dismissLoadingDialog();
                    picKeyArray[submitType] = "";
                    ToastUtils.makeText(mContext, msg.getData().getString("failReason"), ToastUtils.LENGTH_SHORT).show();
                    break;
                case 6:
                    //上传取消
                    dismissLoadingDialog();
                    picKeyArray[submitType] = "";
                    ToastUtils.makeText(mContext, "图片上传取消", ToastUtils.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_certify_drivelicense;
    }

    @Override
    public void initView() {

    }

    @OnClick({R.id.title_back, R.id.iv_drive_qian, R.id.iv_drive_hou, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.iv_drive_qian:
                submitType = 3;
                Intent intent_drive0 = new Intent(mContext, CameraActivity.class);
                intent_drive0.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent_drive0.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                intent_drive0.putExtra("submitType", submitType);
                startActivityForResult(intent_drive0, submitType);
                break;
            case R.id.iv_drive_hou:
                submitType = 4;
                Intent intent_drive1 = new Intent(mContext, CameraActivity.class);
                intent_drive1.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent_drive1.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                intent_drive1.putExtra("submitType", submitType);
                startActivityForResult(intent_drive1, submitType);
                break;
            case R.id.tv_next:
                commitDrivingLicense();
                break;
        }
    }

    private void commitDrivingLicense() {
        showLoadingDialog();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            jsonObject.put("licensePicture", picKeyArray[3]);
            jsonObject.put("licensePictureCopy", picKeyArray[4]);
            if (drivingCard != null) {
                jsonObject.put("licenseInfoJsonStr", drivingCard);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).commitDrivingLicense(body).enqueue(new Callback<CommitDriveLicenseBean>() {
            @Override
            public void onResponse(Call<CommitDriveLicenseBean> call, Response<CommitDriveLicenseBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if ("1002032".equals(response.body().getAttachment().getCode())) {
                            //机审通过
                            startActivity(new Intent(mContext, CertifyCardFinishActivity.class));
                        } else {
                            startActivity(new Intent(mContext, CertifyCardInActivity.class));
                        }
                        AppManager.getAppManager().finishActivity();
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommitDriveLicenseBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == submitType && resultCode == Activity.RESULT_OK && data != null) {   //获得图片后

            if (submitType == 3) {
                drivingCard = data.getStringExtra("DRIVING_JSON");
            }
            filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
            originalFile = new File(filePath);
            Luban.with(mContext)
                    .load(originalFile)  //传入要压缩的图片
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            Message message = new Message();
                            message.arg1 = 1;
                            handler.sendMessage(message);
                        }

                        @Override
                        public void onSuccess(File file) {
                            Message message = new Message();
                            message.arg1 = 2;
                            compressFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + SDCardUtils.createFileName(((MyApplication) getApplication()).getUid()) + ".jpg");
                            file.renameTo(compressFile);
                            handler.sendMessage(message);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Message message = new Message();
                            message.arg1 = 3;
                            handler.sendMessage(message);
                        }
                    }).launch();    //启动压缩
        }

    }

    private void uploadImage(final File picFile) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        picKeyArray[submitType] = getFileNameNoEx(picFile);
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                picKeyArray[submitType], new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        Message message = new Message();
                                        message.arg1 = 4;
                                        Bundle b = new Bundle();
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        Message message = new Message();
                                        message.arg1 = 5;
                                        Bundle b = new Bundle();
                                        b.putString("failReason", failReason);
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }
                                });

                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /*
   * Java文件操作 获取不带扩展名的文件名
   */
    public String getFileNameNoEx(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

}
